"""
二、写一个文件传输服务器和客户端

1. 通过命令行参数指定ip和端口
2. 每次只传输一个文件
3. 服务器持续运行，不断地接收多个客户端同时上传文件
"""

import sys
import os
import socket
import signal
from datetime import datetime
import multiprocessing as mp


def receive(sock):
    dt = datetime.now()
    fname = dt.strftime('%Y%m%d%H%M%S') + str(dt.microsecond)
    fpath = os.path.join(base_dir, fname)
    f = open(fpath, 'wb')
    bs = 16384
    while True:
        chunk = sock.recv(bs)
        if not chunk:
            break
        f.write(chunk)


def sigchld_handler(signum, stackframe):
    os.waitpid(-1, os.WNOHANG)


base_dir = 'uploaded'


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('usage: %s ip port' % os.path.basename(sys.argv[0]))
        exit(1)
    ip = sys.argv[1]
    port = int(sys.argv[2])

    # 设置SIGCHLD信号的处理函数，用来清理退出的子进程
    signal.signal(signal.SIGCHLD, sigchld_handler)

    # 监听，持续接受客户端同时上传数据，存放到文件中
    # 用多进程的方式来实现并发
    sock = socket.socket()
    sock.bind((ip, port))
    sock.listen(3)

    while True:
        client, addr = sock.accept()
        print('client %s:%s connected' % addr)
        p = mp.Process(target=receive, args=(client,))
        p.start()
